import React, {Component} from 'react';
import {ajax, promptBox, toast, base, cacheTools} from 'nc-lightapp-front';
import {chectFormAction, setFormAttrAndValue} from '../../../../../public/functions/checkFormAction'
const {NCModal, NCButton, NCRadio} = base
import './index.less'
import {saveValidate } from 'src/hrpub/common/utils/utils';
let pk_psnjobs = []
class AddForm extends Component{
    constructor(props) {
        super(props);
        // debugger
        this.state = {
            formVisible: false,
            step: '0',
            pk_psnjobs: [],
            editColumn: [], // 可编辑的键
            contractnum: '', // 变更前合同编号
            addSaveUrl: 'MakeAddSaveAction',
            savedData: null,
            showModal: false,
            selectData: [],
            selectedValue: '1', // 批量续签方式 '1' 按统一期限进行续签 '2' 统一续签到某个日期
            rollBackFlag: null,
            extendParam: null,
            selectDataLen: 0,
            extendtype: null,
            config: props.config
        }
    }
    // 将表单模板key值改变
    setDataBeforeFormKey (props) {
        let state = this.state
        // 改dataAfter的键名
        let meta = props.meta.getMeta()['dataBefore_add']
        let meta2 = props.meta.getMeta()['dataAfter_add']
        meta.items.map(obj => {
            obj.attrcode = obj.attrcode + '_old'
            switch (obj.attrcode) {
                case 'creator_old':
                    obj.visible = false
                    break;
                case 'creationtime_old':
                    obj.visible = false
                    break;
                case 'modifier_old':
                    obj.visible = false
                    break;
                case 'modifiedtime_old':
                    obj.visible = false
                    break;
                default:break;
            }
        })
        meta2.items.map(obj => {
            switch (obj.attrcode) {
                case 'creator':
                    obj.visible = false
                    break;
                case 'creationtime':
                    obj.visible = false
                    break;
                case 'modifier':
                    obj.visible = false
                    break;
                case 'modifiedtime':
                    obj.visible = false
                    break;
                default:break;
            }
        })
    }
    // 提示选择续签方式
    selectExtendStyle () {
        this.setState({
            showModal: true,
        })
    }
    // 下一步方法
    nextHandle (selectData, extendtype) {
        let props = this.props
        let {form, config, pkOrg} = props
        let selectDataLen = selectData.length
        pk_psnjobs = selectData.map(function (item) {
            return item.data.values.pk_psnjob.value
        })
        let paramObj = {
            pageCode: config.pagecode,
            appCode: config.appcode,
            areaCode: 'dataBase,dataBefore,dataAfter',
            pk_psnjobs: pk_psnjobs,
            extendtype: extendtype ? extendtype : parseInt(this.state.selectedValue),
            pk_org: pkOrg
        }
        if (selectDataLen < 2) {
            delete paramObj.extendtype
        }
        ajax({
            url: '/nccloud/hrcm/common/DataInitAction.do', // editColumn
            data: paramObj,
            success: (result) => {
                if (result.success) {
                    let data = result.data
                    let extendParam = data.extendParam
                    let rows = data.resultData.dataBase_add.rows
                    let rollBackFlag =  data.resultData.rollBackFlag
                    let values = rows[0].values
                    let template = {
                        dataAfter_add: data.template.dataAfter_add,
                        dataBase_add: data.template.dataBase_add,
                        dataBefore_add: data.template.dataBefore_add,
                        formrelation: data.template.formrelation
                    }
                    props.meta.addMeta(template);
                    // this.setDataBeforeFormKey(props)
                    let contractnum = values.contractnum.value
                    // 获取可编辑的key
                    let items = props.meta.getMeta()['dataAfter_add'].items
                    let len = items.length 
                    let editColumn = []
                    for (let i=0;i < len; i++) {
                        if (items[i].visible === true && items[i].disabled === false) {
                            editColumn.push(items[i].attrcode)
                        }
                    }
                    this.setState({
                        formVisible: true,
                        editColumn,
                        contractnum,
                        rollBackFlag,
                        extendParam,
                        selectDataLen,
                        extendtype
                    }, function () {
                        form.setAllFormValue({'dataBase_add': {rows: rows}})
                        form.setFormItemsDisabled('dataBase_add', {termmonth_old: true, enddate_old: true})
                        form.setFormItemsRequired('dataBase_add', {termmonth_old: false, enddate_old: false})
                        form.setFormStatus('dataBase_add', 'edit')
                        let attrMap = data.attrMap
                        let valueMap = data.valueMap
                        setFormAttrAndValue(attrMap, valueMap, props, 'dataBase_add', ['dataBase_add', 'dataAfter_add'])
                    })
                }
            },
            error: (err) => {
                this.prevHandle()
                toast({
                    color: 'danger',
                    content: err.message
                })
                throw err
            }
        })
    }
    // 完成方法 调用新增保存接口
    doneHandle (extendtype) {
        let props = this.props
        let state = this.state
        let {form, json, cardPagination, config} = props
        if (!form.isCheckNow('dataBase_add')) {
            return false
        }
        saveValidate(props, 'dataBase_add', 'dataBase_add', ['dataBefore_add', 'dataAfter_add'] , 'extcard').then(() => {
            let formDataRows = form.getAllFormValue('dataBase_add').rows
            let formData = {
                model: {
                    rows: formDataRows
                }
            }
            let paramObj = {
                step: state.step,
                pk_org: props.pkOrg,
                appCode: config.appcode,
                modename: 'hi_psndoc_ctrt',
                formData: formData,
                editColumn: state.editColumn,
                extendtype: extendtype ? extendtype : parseInt(state.selectedValue)
            }
            if (state.selectDataLen < 2) {
                delete paramObj.extendtype
            }
            if (parseInt(state.step) > 2) {
                paramObj = {
                    step: state.step,
                    pk_org: props.pkOrg,
                    appCode: config.appcode,
                    savedData: state.savedData
                }
                formData = null
                formDataRows = null
            }
            ajax({
                url: `/nccloud/hrcm/make/${state.addSaveUrl}.do`,
                data: paramObj,
                success: (result) => {
                    if (result.success) {
                        this.setState({
                            step: result.data.step
                        }, function () {
                            if (result.data.step === '3') {
                                let savedData = result.data.savedData
                                this.setState({
                                    savedData: savedData,
                                    addSaveUrl: 'MakeAddSaveActionAfter'
                                }, function () {
                                    this.doneHandle(extendtype)
                                    if (props.returnListOrCard && props.returnListOrCard() === 'cardList') {
                                        let pk_psndoc_sub = savedData[savedData.length - 1]
                                        props.initDataShow(pk_psndoc_sub)
                                        let allpks = cacheTools.get('allpks')
                                        allpks.push(pk_psndoc_sub)
                                        cardPagination.setCardPaginationId({id: pk_psndoc_sub, status: 1})
                                    }
                                })
                                return false
                            }
                            let title = json['cm6011-000126'] // 确定继续
                            if (result.data.step === '4') {
                                title = json['cm6011-000121'] // 确认生效
                            }
                            if (result.data.step !== '99') {
                                this.addSaveAfterTips(result.data.msg, title)
                            } else {
                                toast({
                                    color: 'success',
                                    content: json['cm6011-000122'] // 生效成功
                                })
                                this.setState({
                                    step: '0',
                                    addSaveUrl: 'MakeAddSaveAction'
                                })
                                props.setNewIncreasedDis(false)
                                if (props.refreshTableList) {
                                    props.refreshTableList()
                                }
                                if (props.setIsInterrupt) {
                                    props.setIsInterrupt(true)
                                }
                            }
                        })
                    }
                }
            })
        })
    }
    // 点击生效之后的提示
    addSaveAfterTips (message, title) {
        let json = this.props.json
        const {extendtype} = this.state
        promptBox({
            color: 'warning',
            title: title, // 确认继续
            content: message,
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: json['cm6011-000057'], // 是
            cancelBtnName: json['cm6011-000058'], // 否
            beSureBtnClick: this.doneHandle.bind(this, extendtype),
            hasCloseBtn:false,
            cancelBtnClick: this.cancelBtnClick.bind(this, title)
        })
    }
    cancelBtnClick (title) {
        let props = this.props
        let state = this.state
        let json = props.json
        this.setState({
            step: '0'
        })
        if (title === json['cm6011-000121']) {
            props.setNewIncreasedDis(false)
            if (props.refreshTableList) {
                props.refreshTableList()
            }
        }
        if (props.setIsInterrupt) {
            props.setIsInterrupt(true)
        }
        if (props.jumpToNode && title === json['cm6011-000121']) {
            props.jumpToNode(state.savedData, 'extend')
        }
    }
    onClose () {
        this.props.setNewIncreasedDis(false)
        this.setState({
            step: '0'
        })
        if (this.state.rollBackFlag) {
            this.CodeRollBaceAction()
        }
        if (this.props.setIsInterrupt) {
            this.props.setIsInterrupt(true)
        }
    }
    // 上一步的回调
    prevHandle () {
        this.setState({
            step: '0'
        })
        if (this.state.rollBackFlag) {
            this.CodeRollBaceAction()
        }
        if (this.props.setIsInterrupt) {
            this.props.setIsInterrupt(true)
        }
    }
    // 调用合同编码回滚接口
    CodeRollBaceAction () {
        let props = this.props
        let state = this.state
        let contractnum = state.contractnum
        let codeList = []
        if (contractnum && contractnum.indexOf(',') !== -1) {
            codeList = contractnum.split(',')
        } else {
            codeList.push(contractnum) 
        }
        let paramObj = {
            pk_org: props.pkOrg,
            codeList: codeList
        }
        ajax({
            url: '/nccloud/hrcm/common/CodeRollBackAction.do',
            data: paramObj,
            success: (result) => {
                if (result.success) {
                    
                }
            }
        })
    }
    // 表单改变之后的触发函数
    onAfterEvent (props, moduleId, key, value, oldValue) {
        let { config } = this.state;
        chectFormAction(key, 'dataBase_add', props, ['dataBase_add', 'dataAfter_add'], config.appcode, this.state.extendParam)
    }
    //编辑FormCard前方法
    handleEditBefore(props, moduleId, key, value,data){
        if(key == 'pk_conttext'){
            let meta = this.props.meta.getMeta();
            let pk_org = this.props.pkOrg;
            meta['dataAfter_add'].items.find(item => item.attrcode === key).queryCondition = function () {
                return {
                    "pk_org": pk_org,
                    "GridRefActionExt": "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder"
                }
            };
            this.props.meta.setMeta(meta);
        }
        return true;
    }
    // 弹窗关闭函数
    close () {

    }
    // 点击确定按钮
    clickConfirmBtn () {
        this.setState({
            showModal: false
        }, function () {
            if (this.props.isExtendAdd) {
                this.props.nextHandleFn()
            }
        })
    }
    // 点击关闭按钮
    clickCloseBtn () {
        this.setState({
            showModal: false
        })
    }
    // 切换续签方式的回调
    handleChange (value) {
        this.setState({
            selectedValue: value
        })
    }
    render () {
        const {form, json} = this.props
        return (
            <div className="addFormCon">
                {
                    this.state.formVisible ? 
                    form.createForm('dataBase_add', {
                        expandArr: ['dataAfter_add'],
                        onAfterEvent: this.onAfterEvent.bind(this),
                        onBeforeEvent: this.handleEditBefore.bind(this)
                    }) : ''
                }
                <NCModal 
                    show={this.state.showModal}
                    onHide={this.close.bind(this)}
                    size='sm'
                    dialogClassName='ncmodel'>
                        <NCModal.Header>
                            {/* 提示 */}
                            <NCModal.Title>{json['cm6011-000030']}</NCModal.Title>
                        </NCModal.Header>
                        <NCModal.Body>
                            {/* 系统将按所选人员中每个人到期日期的第二天开始续签，请选择续签方式 */}
                            <div className="ncmodelTxt">{json['cm6011-000127']}</div>
                            <NCRadio.NCRadioGroup
                                name="renewalStyle"
                                selectedValue={this.state.selectedValue}
                                onChange={this.handleChange.bind(this)}>
                                    {/* 按统一期限进行续签 */}
                                    <NCRadio value="1" >{json['cm6011-000128']}</NCRadio>
                                    {/* 统一续签到某个日期 */}
                                    <NCRadio value="2" >{json['cm6011-000098']}</NCRadio>
                            </NCRadio.NCRadioGroup>
                        </NCModal.Body>
                        <NCModal.Footer>
                            {/* 确认 */}
                            <NCButton onClick={this.clickConfirmBtn.bind(this)} color="primary">{json['cm6011-000056']}</NCButton>
                            {/* 关闭 */}
                            <NCButton onClick={this.clickCloseBtn.bind(this)}>{json['cm6011-000129']}</NCButton>
                        </NCModal.Footer>
                </NCModal>
            </div>
        )
    }
}
export default AddForm